package com.voicechat.firstmet.client;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.google.gson.Gson;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketFrame;
import com.voicechat.firstmet.App;
import com.voicechat.firstmet.activity.InviteVoiceChatActivity;
import com.voicechat.firstmet.bean.VoiceChatIngWSBean;
import com.voicechat.firstmet.imcontrol.BroadcastManager;
import com.voicechat.firstmet.imcontrol.MessageEvent;

import org.json.JSONObject;

import java.util.List;
import java.util.Map;

/**
 * 继承默认的监听空实现WebSocketAdapter,重写我们需要的方法
 * onTextMessage 收到文字信息
 * onConnected 连接成功
 * onConnectError 连接失败
 * onDisconnected 连接关闭
 */
public class WsListener extends WebSocketAdapter {
    private static String TAG = "WsListener";
    private static WsListener wsListener;
    private WsStatus mStatus;
    private TextMessage textMessage;
    private OnConnectIng onConnectError;
    private OnTextMessage onTextMessage;

    public void setOnTextMessage(OnTextMessage onTextMessage) {
        this.onTextMessage = onTextMessage;
    }

    public void setTextMessage(TextMessage textMessage) {
        this.textMessage = textMessage;
    }

    public WsListener() {
    }

    public static WsListener getInstance(){
        if(wsListener == null){
            synchronized (WsManager.class){
                if(wsListener == null){
                    wsListener = new WsListener();
                }
            }
        }
        return wsListener;
    }

    public void setOnConnectError(OnConnectIng onConnectError) {
        this.onConnectError = onConnectError;
    }

    @Override
    public void onTextMessage(WebSocket websocket, String text) throws Exception {
        //super.onTextMessage(websocket, text);
        Log.i(TAG,"onTextMessage"+text);
        //textMessage.sendMessage(text);
        JSONObject jsonObject = new JSONObject(text);
        if(jsonObject.has("code")){
            int code = jsonObject.getInt("code");
            Intent intent = null;
            switch (code){
                case 2001://呼叫方收到邀请成功回调
                    Log.i(TAG, "onTextMessage: ----------2001------");
                    break;
                case 2002://接听者收到邀请消息
                    Log.i(TAG, "onTextMessage: ----------2002------");
                    intent = new Intent(App.getContext(), InviteVoiceChatActivity.class);
                    Gson gson = new Gson();
                    VoiceChatIngWSBean voiceChatIngWSBean = gson.fromJson(text, VoiceChatIngWSBean.class);
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("object",voiceChatIngWSBean.getObject());
                    //bundle.putString("type","0");
                   // bundle.putString("flag","0");
                    intent.putExtra("type","0");
                    intent.putExtra("flag","0");
                    intent.putExtra("bundle",bundle);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    App.getContext().startActivity(intent);
                    break;
                case 2003://接听方接听了消息
                    Log.i(TAG, "onTextMessage: ----------2003------");
                    BroadcastManager.getInstance(App.getContext()).sendBroadcast("2003");
                    break;
                case 2004://向服务器发送通话计时扣费消息后的回调
                    Gson gson2004 = new Gson();
                    VoiceChatIngWSBean voiceChatIngWSBean2004 = gson2004.fromJson(text, VoiceChatIngWSBean.class);
                    Log.i(TAG, "onTextMessage: ---voiceChatIngWSBean2004----"+voiceChatIngWSBean2004.getObject().toString());
                    BroadcastManager.getInstance(App.getContext()).sendBroadcast("2004",voiceChatIngWSBean2004.getObject());
                    /*if(voiceChatIngWSBean2004.getObject().getGold() < 0){
                        BroadcastManager.getInstance(App.getContext()).sendBroadcast("2004");
                    }*/
                    break;
                case 2005:
                    break;
                case 2006://向服务器发送礼物后的回调
                    Gson gson2 = new Gson();
                    VoiceChatIngWSBean voiceChatIngWSBean2 = gson2.fromJson(text, VoiceChatIngWSBean.class);
                    BroadcastManager.getInstance(App.getContext()).sendBroadcast("2006",voiceChatIngWSBean2.getObject());
                    break;
                case 2007://收到礼物的回调
                    Gson gson1 = new Gson();
                    VoiceChatIngWSBean voiceChatIngWSBean1 = gson1.fromJson(text, VoiceChatIngWSBean.class);
                    BroadcastManager.getInstance(App.getContext()).sendBroadcast("2007",voiceChatIngWSBean1.getObject());
                    break;
                case 2008://对方退出房间的回调（拒接和挂断）
                   // new InviteVoiceChatActivity().setMessage();
                   // onTextMessage.onTextMessage(text);
                    Log.i(TAG, "onTextMessage: -----BroadcastManager-------2008----------");
                    BroadcastManager.getInstance(App.getContext()).sendBroadcast("2008");
                    break;
                case 2009://对方接听失败(进入房间失败)
                    BroadcastManager.getInstance(App.getContext()).sendBroadcast("2009");
                    break;
                case 2010://对方网络异常
                    BroadcastManager.getInstance(App.getContext()).sendBroadcast("2010");
                    break;
                case 2011://自己掉线
                    BroadcastManager.getInstance(App.getContext()).sendBroadcast("2011");
                    break;
                case 2015://挂断
                    BroadcastManager.getInstance(App.getContext()).sendBroadcast("2015");
                    break;
            }
        }
    }
    @Override
    public void onConnected(WebSocket websocket, Map<String, List<String>> headers)
            throws Exception {
        super.onConnected(websocket, headers);
       // BroadcastManager.getInstance(App.getContext()).sendBroadcast(MessageEvent.WS_HEAD);
        Log.i(TAG,"连接成功");
        onConnectError.onConnectSuccess(websocket);
        setStatus(WsStatus.CONNECT_SUCCESS);
    }
    @Override
    public void onConnectError(WebSocket websocket, WebSocketException exception)
            throws Exception {
        super.onConnectError(websocket, exception);
        Log.i(TAG,"连接错误"+exception.getError().toString());
        setStatus(WsStatus.CONNECT_FAIL);
        onConnectError.onConnectError(exception);
        BroadcastManager.getInstance(App.getContext()).sendBroadcast(MessageEvent.WS_MANAGER);
    }
    @Override
    public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer)
            throws Exception {
        super.onDisconnected(websocket, serverCloseFrame, clientCloseFrame, closedByServer);
        Log.i(TAG,"断开连接");
        setStatus(WsStatus.CONNECT_FAIL);
        BroadcastManager.getInstance(App.getContext()).sendBroadcast(MessageEvent.WS_MANAGER);
    }
    public void setStatus(WsStatus status){
        this.mStatus = status;
    }
    /**
     * @method
     * @description 得到链接状态
     * @date: 2018/11/21 11:05
     * @author: ljp
     * @return
     */
    public WsStatus getStatus(){
        return mStatus;
    }
    //长链接接收消息回调
    interface TextMessage{
        void sendMessage(String text);
    }
    //链接错误回调
    public interface OnConnectIng{
        void onConnectError(WebSocketException exception);
        void onConnectSuccess(WebSocket websocket);
    }
    enum WsStatus {
        CONNECT_SUCCESS,//连接成功
        CONNECT_FAIL,//连接失败
        CONNECTING;//正在连接
    }

    public interface OnTextMessage{
        void onTextMessage(String text);
    }
}
